﻿package birdry.media
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	
	/**
	* ...
	* @author 
	*/
	public class SoundController extends EventDispatcher	{
		
		var sound:Sound;
		var channel:SoundChannel;
		var loop:Boolean;
		var soundTransform:SoundTransform;
		var playFlag:Boolean;
		
		public function SoundController(loop:Boolean = true): void	{
			this.loop = loop;
			setLayout();
			addEvent();
		}
		
		private function setLayout():void		{
			sound = new Sound();
			soundTransform = new SoundTransform();
		}
		
		private function addEvent():void		{
			
		}
		
		private function onSoundComplete(e: Event ): void	{
			channel = sound.play();
		}
		
		public function get url(): String	{
			return sound.url;
		}
		public function set url( value: String ): void	{
			sound.load( new URLRequest( value) );
		}
		
		public function get volume(): Number	{
			return channel.soundTransform.volume;
		}
		public function set volume( value: Number ): void	{
			if (!channel)	return;
			soundTransform.volume = value;
			channel.soundTransform = soundTransform;
		}
		
		public function play(startTime:Number=0, loops:uint=1): void	{
			if (playFlag)	return;
			playFlag = true;
			channel = sound.play(startTime, loops);
			if(loop)		channel.addEventListener("soundComplete", onSoundComplete);
		}
		
		public function stop(): void	{
			if (!playFlag)	return;
			playFlag = false;
			channel.stop();
			if(loop)		channel.removeEventListener("soundComplete", onSoundComplete);
		}
	}	// class
	
}	// package